<?php

require(dirname(__FILE__) . '/./../plugins/cos.php');

use Qcloud_cos\Auth;
use Qcloud_cos\Cosapi;

class TaskController extends CloudControllerBase
{


    /******************************   添加分派    ***********************************************************/
    //添加分派
    public function addDispatchTaskAction()
    {

        $user = $this->getMonitorLoginUser(true);
        if ($user) {
            //$userId=$user->userId;
            $workId = $this->getQuery("work_id");
            if ($workId) {
                $projectWork = $this->fetchOne("select * from project_work where id=$workId");
                $projectId = $projectWork["project_id"];
                $projectInfo = $this->_getProjectInfo($projectId);
                $dispatchData = $this->fetchAll(
                    "select a.*,u.nickname from project_assign a
left join user u on u.id=a.assign_to_user_id
where projectWork_id=$workId order by created_at asc"
                );
                $this->view->setVars(
                    array(
                        "projectWork" => json_encode($projectWork),
                        "dispatchList" => json_encode($dispatchData),
                        "projectInfo" => json_encode($projectInfo),
                        "curUser" => json_encode($user)
                    )
                );
            } else {
                $this->view->setVars(
                    array(
                        "curUser" => json_encode($user)
                    )
                );
            }
        }

    }

    //获取我的项目列表
    public function doListMyProjectAction()
    {

        if ($this->isMonitorSubsystemAdminUser()
            ||
            $this->isMonitorAdminUser()
        ) {
            $user = $this->getMonitorLoginUser();
            $userId = $user->userId;
            $action = $this->getRequestAction();
            switch ($action) {
                case  $this::REQUEST_ACTION_DELETE: {
                };
                    break;
                case  $this::REQUEST_ACTION_LIST: {

                    $tableName = "(SELECT * FROM 
                (SELECT id,local_id,version,project_name,on_server,created_at,updated_at
                FROM project WHERE user_id = $userId AND is_removed = 0 ORDER BY version DESC)
 AS a GROUP BY local_id)";

                    $this->postQueryByPage(array(
                        "id" => "ID",
                        "project_name" => "工程名称",
                        "created_at" => "创建时间",
                        "updated_at" => "更新时间"
                    ), $tableName, array(
                        ["project_name", "like", "%", "%"],

                    ), "", "id");
                };
                    break;
            }
        } else {
            $this->returnError("操作权限错误");
        }

    }

    //列表我的用户
    public function doListMyUsersAction()
    {
        if ($this->isMonitorAdminUser()
            ||
            $this->isMonitorSubsystemAdminUser()
        ) {
            $user = $this->getMonitorLoginUser();
            $userId = $user->userId;
            $action = $this->getRequestAction();
            switch ($action) {
                case  $this::REQUEST_ACTION_DELETE: {
                };
                    break;
                case  $this::REQUEST_ACTION_LIST: {

                    $subsystemId = $user->subsystemId;
                    $tableName = "(
select u.*,real_name from user u inner join 
(select * from bind_user_system where system_id=$subsystemId) as b on b.user_id=u.id)";

                    $this->postQueryByPage(array(
                        "id" => "ID",
                        "phone" => "电话",
                        "real_name" => "姓名",
                        "email" => "邮箱",
                        "city" => "城市",
                        "company" => "公司"
                    ), $tableName, array(
                        ["real_name", "like", "%", "%"],
                        ["phone", "like", "%", "%"],
                        ["company", "like", "%", "%"],
                        ["city", "like", "%", "%"],
                        ["email", "like", "%", "%"]
                    ), "", "id");
                };
                    break;
            }
        } else {
            $this->transferErrorPage("权限错误", "您没有权限访问");
        }


    }

    //获取项目信息
    public function doProjectInfoAction()
    {
        if (!$this->isMonitorAdminUser() && !$this->isMonitorSubsystemAdminUser()) {
            $this->returnError("操作权限错误");
        }
        $user = $this->getMonitorLoginUser();
        $this->checkRequestParams(array(
                array(
                    "key" => "project_id",
                    "type" => "presence&number",
                    "message" => "project_id为空"),
            )
        );
        $projectId = $this->getPost("project_id");
        //获取工程名称,获取block信息,获取任务信息
        $project = $this->_getProjectInfo($projectId);
        $this->returnJson($project);

    }

    private function _getProjectInfo($projectId)
    {
        //该部分,可以单独抽离出来
        $sql = "select * from project where id=$projectId";
        $project = $this->fetchOne($sql);

        if (empty($project)) {
            $this->returnError("项目id:$projectId 不存在。");
        }
        $projectId = $project["id"];
        $sql = "select * from survey_block where project_id = $projectId";
        $blocks = $this->fetchAll($sql);

        $sql = "select id, '{$project["local_id"]}' as project_id, lng, lat, name, elevation from project_point where project_id = $projectId";
        $points = $this->fetchAll($sql);

        $project["points"] = $points;

        foreach ($blocks as &$block) {
            $blockId = $block["id"];
            $sql = "select * from flight_task where survey_block_id = $blockId";
            $tasks = $this->fetchAll($sql);

            foreach ($tasks as &$task) {
                $task["id"] = $task["flight_task_guid"];
                $task["survey_block_id"] = $block["local_id"];
                unset($task["local_id"]);
            }

            $block["tasks"] = $tasks;
            $block["id"] = $block["survey_area_guid"];
            $block["project_id"] = $project["local_id"];
            unset($block["local_id"]);

        }
        $project["blocks"] = $blocks;
        $project["id"] = $project["local_id"];
        unset($project["local_id"]);
        return $project;
    }

    /******************************   分派列表    ***********************************************************/

    public function listAction()
    {
        $user = $this->getMonitorLoginUser();
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {


                if ($this->isMonitorAdminUser()) {
                    $tableName = "(SELECT
	w.*, a.task_total
FROM
	project_work w
LEFT JOIN (
	SELECT
		projectWork_id,
		count(task_local_id) AS task_total
	FROM
		project_assign
	GROUP BY
		projectWork_id
) a ON a.projectWork_id = w.id)";
                } else {
                    $userId = $user->userId;
                    if ($this->isMonitorSubsystemAdminUser()) {
                        $tableName = "(SELECT
	w.*, a.task_total
FROM
	project_work w
LEFT JOIN (
	SELECT
		projectWork_id,
		count(task_local_id) AS task_total
	FROM
		project_assign
	GROUP BY
		projectWork_id
) a ON a.projectWork_id = w.id where w.user_id=$userId )";
                    } else {
                        $this->returnError("权限错误", "您没有操作权限");
                    }
                }

                $this->postQueryByPage(array(
                    "id" => "ID",
                    "work_name" => "工作名称",
                    "task_total" => "分派任务数",
                    "created_at" => "创建时间",
                ), $tableName, array(
                    ["work_name", "like", "%", "%"],
                    ["id", "=", "", ""],
                    ['created_at_start', '>=', '', '', "created_at"],
                    ['created_at_end', '<=', '', '', "created_at"]
                ), "created_at desc", "id");
            };
                break;
        }

    }


    public function listMyAction()
    {
        $user = $this->getMonitorLoginUser();
        $userId = $user->userId;
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {

                $tableName = "(SELECT
	a.*, p.project_name
FROM
	project_assign a
LEFT JOIN (
	SELECT
		local_id,
		project_name
	FROM
		project
	GROUP BY
		local_id
) p ON p.local_id = a.project_local_id 
WHERE
	a.assign_to_user_id =$userId
	)";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "project_name" => "工程名称",
                    "status" => "当前状态",
                    "created_at" => "分派时间",
                ), $tableName, array(
                    ["project_name", "like", "%", "%"],
                    ["id", "=", "", ""],
                    ["status", "=", "", ""],
                    ["created_at_start", ">=", "", "", "created_at"],
                    ["created_at_end", "<=", "", "", "created_at"],
                ), "created_at desc", "id");
            };
                break;
        }
        $this->view->setVars(array(
            "curUser" => json_encode($user)
        ));
    }


    /**
     * @param $name
     * @param $value
     * @return mixed
     */
    public function filedItemChanged($table, $name, $value)
    {
        switch ($name) {
            case "company":
            case "city":
            case "real_name":{
                if($value==null){
                    return "";
                }
            };break;
            case "task_total": {
                if (!$value) {
                    return "0";
                }
            };
                break;
        }
        return $value;
    }


    public function projectAction()
    {
        $user = $this->getMonitorLoginUser();

        // 获得request
        $validation = new Phalcon\Validation();
        $validation->add('id', new PresenceOf(array('message' => '项目编号不能为空')));

        $this->checkRequest($validation, $this->request->getPost());

        $localId = $this->getPost("id", '', 'striptags');
//         $this->checkRequest($validation, $this->request->getQuery());

//         $localId= $this->getQuery("id", '', 'striptags');

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "get userId:" . $user->userId . ", id:" . $localId . "\r\n", FILE_APPEND);

        $sql = "select id, local_id, project_name, created_at, updated_at, version, center_position_lng, center_position_lat, map_scale, user_id from project where user_id = " . $user->userId . " and local_id = '$localId' and is_removed = false order by version desc limit 1";
        $project = $this->fetchOne($sql);

        if (empty($project)) {
            $this->returnError("项目id:$localId 不存在。");
        }
        $projectId = $project["id"];
        $sql = "select id, local_id, project_id, created_at, updated_at, survey_area_name, block_type, survey_area_coordinate_points, home_lng, home_lat, work_area, work_time from survey_block where project_id = $projectId";
        $blocks = $this->fetchAll($sql);

        $sql = "select id, '{$project["local_id"]}' as project_id, lng, lat, name, elevation from project_point where project_id = $projectId";
        $points = $this->fetchAll($sql);

        $project["points"] = $points;

        foreach ($blocks as &$block) {
            $blockId = $block["id"];
            $sql = "select * from flight_task where survey_block_id = $blockId";
            $tasks = $this->fetchAll($sql);

            foreach ($tasks as &$task) {
                $task["id"] = $task["flight_task_guid"];
                $task["survey_block_id"] = $block["local_id"];
                unset($task["local_id"]);
            }

            $block["tasks"] = $tasks;
            $block["id"] = $block["local_id"];
            $block["project_id"] = $project["local_id"];
            unset($block["local_id"]);

        }
        $project["blocks"] = $blocks;
        $project["id"] = $project["local_id"];
        unset($project["local_id"]);

        $this->returnJson($project);

    }

    // 查询我的分享接口    列出全部分享的项目和被分享的项目，按照时间倒序排序
    public function assignListAction()
    {
        $user = $this->getMonitorLoginUser();

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "listAction userId:$user->userId \r\n", FILE_APPEND);

        $sql = "select a.*,p.project_name from project_assign as a LEFT JOIN user as u on a.assign_to_user_id=u.id LEFT JOIN project as p on a.project_id=p.id where a.assign_from_user_id = $user->userId order by version desc";
        $sendRecords = $this->fetchAll($sql);

        $sql = "select a.*,p.project_name from project_assign as a LEFT JOIN user as u on a.assign_from_user_id=u.id LEFT JOIN project as p on a.project_id=p.id where a.assign_to_user_id = $user->userId order by version desc";
        $retrieveRecords = $this->fetchAll($sql);

        foreach ($retrieveRecords as &$record) {
            $record["save_as"] = 0;
            if ($record["status"] == 0) {

                $assign_log = null;
                $local_id = null;
                // 检查项目是否存在，如果存在，则需要显示另存为接口
                $sql = "SELECT * FROM project_assign where assign_to_user_id = $user->userId and project_local_id = '{$record["project_local_id"]}' and survey_local_id = '{$record["survey_local_id"]}' and task_local_id = '{$record["task_local_id"]}' and status=2 order by updated_at desc";
                $assign_log = $this->fetchOne($sql);

                if ($assign_log) {
                    $sql = "SELECT t.* FROM `project` as p left join survey_block as s on p.id=s.project_id left join flight_task as t on s.id = t.survey_block_id where p.user_id = $user->userId and p.is_removed = 0 and p.local_id = '{$assign_log["to_project_local_id"]}' and s.local_id = '{$assign_log["to_survey_local_id"]}' and t.local_id = '{$assign_log["to_task_local_id"]}'";
                    $local_id = $this->fetchColumn($sql);

                    if (!empty($local_id)) {
                        $record["save_as"] = 1;
                    }
                }
            }
        }

        $json = array();
        $json["send"] = $sendRecords;
        $json ["retrieve"] = $retrieveRecords;
        $this->returnJson($json);
    }


    public function addProjectWorkAction()
    {
        $this->checkRequestParams(array(
            array(
                "key" => "project_id",
                "type" => "presence",
                "message" => "项目编号不能为空"
            ),
            array(
                "key" => "task_list",
                "type" => "presence",
                "message" => "分派列表不能为空"
            )
        ));
        $projectId = $this->getPost("project_id", '', 'int');
        $taskList = $this->getPost("task_list");
        $projectWorkId = $this->getPost("project_work_id", '', 'int');
        $message = $this->getPost("message", '', 'striptags');

        if (!$projectWorkId) {
            $projectWorkId = $this->_addProjectWork($projectId);
        }
        if ($projectWorkId) {

            foreach ($taskList as $taskId => $dispatchInfo) {
                //获取task对应的信息
                $this->_addProjectAssign(
                    intval($dispatchInfo["user_id"]),
                    $dispatchInfo["project_local_id"],
                    $dispatchInfo["survey_local_id"],
                    $taskId,
                    $projectWorkId,
                    $message
                );
            }
        }
        $this->returnJson(array(
            'project_work_id' => $projectWorkId,
        ));
    }

    public function getProjectWorkByIdAction()
    {
        $user = $this->getMonitorLoginUser();

        $this->checkRequestParams(array(
            array(
                "key" => "id",
                "type" => "presence",
                "message" => "分派编号不能为空"
            )
        ));

        $id = $this->getPost("id", '', 'int');

        $sql = "select * from project_work where id = " . $id;
        $projectWork = $this->fetchOne($sql);

        if (empty($projectWork)) {
            $this->returnError("项目" . $id . "不存在。");
        } else {

            $this->returnJson($projectWork);
        }

    }


    public function projectAssignAction()
    {
        $user = $this->getMonitorLoginUser();

        // 获得request
        $validation = new Phalcon\Validation();
        $validation->add('user_id', new PresenceOf(array('message' => '用户id不能为空')));
        $validation->add('project_local_id', new PresenceOf(array('message' => '项目编号不能为空')));
        $validation->add('survey_local_id', new PresenceOf(array('message' => '区块编号不能为空')));
        $validation->add('task_local_id', new PresenceOf(array('message' => '任务编号不能为空')));
        $validation->add('project_work_id', new PresenceOf(array('message' => '分派编号不能为空')));

        $this->checkRequest($validation, $this->request->getPost());
        $userId = $this->getPost("user_id", '', 'int');
        $projectWorkId = $this->getPost("project_work_id", '', 'int');
        $projectLocalId = $this->getPost("project_local_id", '', 'striptags');
        $surveyLocalId = $this->getPost("survey_local_id", '', 'striptags');
        $taskLocalId = $this->getPost("task_local_id", '', 'striptags');
        $this->_addProjectAssign($user, $userId, $projectLocalId, $surveyLocalId, $taskLocalId, $projectWorkId);
        $this->returnSuccess('分派成功');

    }

    // 接受接口
    public function acceptAssignAction()
    {

        $user = $this->getMonitorLoginUser();

        // 获得request
        $this->checkRequestParams(array(
            array(
                "key" => "id",
                "type" => "presence&number",
                "message" => "id只能是数字"),
            array(
                "key" => "type",
                "type" => "regex",
                "pattern" => "/^[0-2]$/",
                "message" => "错误类型只能是0~2"
            )
        ));
        $id = $this->getPost("id", '', 'int');
        $type = $this->getPost("type", '', 'int');
        $name = $this->getPost("name", '', 'striptags');
        $message = $this->getPost("message", '', 'striptags');


        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "acceptAction type:$type, name:$name, id:$id\r\n", FILE_APPEND);

        $sql = "select * from project_assign where id = $id";
        $assign = $this->fetchOne($sql);

        if (empty($assign)) {
            $this->returnError("指派id:$id 不存在。");
        }

        if ($assign["status"] != 0) {
            $this->returnError("该项目不是可以接受的状态。");
        }

        $sql = "select * from project where local_id = '{$assign['project_local_id']}' and user_id = {$assign['assign_from_user_id']} order by version desc";
        $project = $this->fetchOne($sql);

        if (empty($project)) {
            $this->returnError("项目id:{$assign['project_local_id']} 不存在。");
        } elseif ($project['is_removed'] == 1) {
            $this->returnError("项目id:{$assign['project_local_id']} 已删除。");
        }
        $fromUserId = $assign["assign_from_user_id"];

        // 设置项目名称
        if (empty($name)) {
            $sql = 'select * from user where id = ' . $assign["assign_from_user_id"];
            $fromUser = $this->fetchOne($sql);
            $projectName = $project["project_name"] . ' from ' . $fromUser['nickname'];
        } else {
            $projectName = $name;
        }

        $sql = "select * from survey_block where local_id = '{$assign['survey_local_id']}' and project_id = " . $project['id'];
        $surveyBlock = $this->fetchOne($sql);

        if (empty($surveyBlock)) {
            $this->returnError("区块id:{$assign['survey_local_id']} 不存在。");
        }

        $sql = "select * from flight_task where local_id = '{$assign['task_local_id']}' and survey_block_id = " . $surveyBlock['id'];
        $flightTask = $this->fetchOne($sql);

        if (empty($flightTask)) {
            $this->returnError("任务id:{$assign['task_local_id']} 不存在。");
        }

        $fromUserId = $assign["assign_from_user_id"];

        if ($type == 0) {
            $sql = "select * from project_assign where assign_to_user_id = $user->userId and project_local_id = '{$assign['project_local_id']}' and status = 2 and type<2 order by updated_at desc";
            $assign_log = $this->fetchOne($sql);

            if ($assign_log) {

                $sql_project = "select * from project where user_id = $user->userId and local_id = '{$assign_log['to_project_local_id']}' and is_removed = 0 order by version desc";
                $toProject = $this->fetchOne($sql_project);

                if ($toProject) {
                    $sql = "select * from project_assign where assign_to_user_id = $user->userId and project_local_id = '{$assign['project_local_id']}' and survey_local_id = '{$assign['survey_local_id']}' and status = 2 and type<2 order by updated_at desc";
                    $assign_block = $this->fetchOne($sql);

                    if ($assign_block) {
                        $sql_block = "select * from survey_block where project_id = {$toProject['id']} and local_id = '{$assign_block['to_survey_local_id']}'";
                        $toBlock = $this->fetchOne($sql_block);

                        if ($toBlock) {
                            $sql = "select * from project_assign where assign_to_user_id = $user->userId and project_local_id = '{$assign['project_local_id']}' and survey_local_id = '{$assign['survey_local_id']}' and task_local_id = '{$assign['task_local_id']}' and status = 2 and type<2 order by updated_at desc";
                            $assign_task = $this->fetchOne($sql);

                            if ($assign_task) {
                                $sql_task = "select * from flight_task where survey_block_id = {$toBlock['id']} and local_id='{$assign_task['to_task_local_id']}'";
                                $toTask = $this->fetchOne($sql_task);

                                if ($toTask) {
                                    $this->returnSuccess('任务已分派');
                                } else {
                                    $toProjectId = $assign_log['to_project_local_id'];
                                    $toBlockId = $assign_block['to_survey_local_id'];
                                    $toTaskId = $this->guid();
                                }
                            } else {
                                $toProjectId = $assign_log['to_project_local_id'];
                                $toBlockId = $assign_block['to_survey_local_id'];
                                $toTaskId = $this->guid();
                            }
                        } else {
                            $toProjectId = $assign_log['to_project_local_id'];
                            $toBlockId = $this->guid();
                            $toTaskId = $this->guid();
                        }
                    } else {
                        $toProjectId = $assign_log['to_project_local_id'];
                        $toBlockId = $this->guid();
                        $toTaskId = $this->guid();
                    }

                    $version = $toProject["version"] + 1;
                } else {
                    $toProjectId = $this->guid();
                    $toBlockId = $this->guid();
                    $toTaskId = $this->guid();

                    $version = 1;
                }
            } else {
                $toProjectId = $this->guid();
                $toBlockId = $this->guid();
                $toTaskId = $this->guid();

                $version = 1;
            }
        } else if ($type == 1) {
            $sql = "select * from project_assign where assign_to_user_id = $user->userId and project_local_id = '{$assign['project_local_id']}' and status = 2 and type<2 order by updated_at desc";
            $assign_log = $this->fetchOne($sql);

            if ($assign_log) {

                $sql_project = "select * from project where user_id = $user->userId and local_id = '{$assign_log['to_project_local_id']}' and is_removed = 0 order by version desc";
                $toProject = $this->fetchOne($sql_project);

                if ($toProject) {
                    $sql = "select * from project_assign where assign_to_user_id = $user->userId and project_local_id = '{$assign['project_local_id']}' and survey_local_id = '{$assign['survey_local_id']}' and status = 2 and type<2 order by updated_at desc";
                    $assign_block = $this->fetchOne($sql);

                    if ($assign_block) {
                        $sql_block = "select * from survey_block where project_id = {$toProject['id']} and local_id = '{$assign_block['to_survey_local_id']}'";
                        $toBlock = $this->fetchOne($sql_block);

                        if ($toBlock) {
                            $sql = "select * from project_assign where assign_to_user_id = $user->userId and project_local_id = '{$assign['project_local_id']}' and survey_local_id = '{$assign['survey_local_id']}' and task_local_id = '{$assign['task_local_id']}' and status = 2 and type<2 order by updated_at desc";
                            $assign_task = $this->fetchOne($sql);

                            if ($assign_task) {
                                $sql_task = "select * from flight_task where survey_block_id = {$toBlock['id']} and local_id='{$assign_task['to_task_local_id']}'";
                                $toTask = $this->fetchOne($sql_task);

                                if ($toTask) {
                                    $toProjectId = $assign_log['to_project_local_id'];
                                    $toBlockId = $assign_task['to_survey_local_id'];
                                    $toTaskId = $assign_task['to_task_local_id'];
                                    $version = $toProject["version"] + 1;
                                } else {
                                    $toProjectId = $assign_log['to_project_local_id'];
                                    $toBlockId = $assign_block['to_survey_local_id'];
                                    $toTaskId = $this->guid();
                                    $version = $toProject["version"] + 1;
                                }
                            } else {
                                $this->returnError('您未拥有当前任务,无法进行覆盖');
                            }
                        } else {
                            $toProjectId = $assign_log['to_project_local_id'];
                            $toBlockId = $this->guid();
                            $toTaskId = $this->guid();
                            $version = $toProject["version"] + 1;
                        }
                    } else {
                        $this->returnError('您未拥有当前测区信息,无法进行覆盖');
                    }
                } else {
                    $toProjectId = $this->guid();
                    $toBlockId = $this->guid();
                    $toTaskId = $this->guid();

                    $version = 1;
                }
            } else {
                $this->returnError('您未拥有当前项目,无法进行覆盖');
            }
        } else if ($type == 2) {
            $toProjectId = $this->guid();
            $toBlockId = $this->guid();
            $toTaskId = $this->guid();
            $version = 1;
        } else {
            $this->returnError("操作类型错误。");
        }

        $this->begin();
        try {
            $project["version"] = $version;
            $project["project_name"] = $projectName;
            $project["local_id"] = $toProjectId;
            $project["user_id"] = $user->userId;
//             $project["share_from_id"] =$share["share_from_user_id"];
            $oldProjectId = $project["id"];
            unset($project["id"]);
            unset($project["created_at"]);

            $projectId = $this->insert("project", $project);

//             if(!empty($message)){
//                 $this->insert("project_share_message", array(
//                         "project_share_id" => $share["id"],
//                         "user_id" => $user["id"],
//                         "type" => 2,
//                         "info" => $message,
//                 ));
//             }

            $sql = "select * from project_point where project_id = $oldProjectId";
            $points = $this->fetchAll($sql);

            foreach ($points as $point) {
                $point["project_id"] = $projectId;

                unset($point["id"]);
                unset($point["created_at"]);
                $this->insert("project_point", $point);
            }
            file_put_contents("./log_" . date("Y-m-d") . ".txt", date("H:i:s", time()) . ':' . __METHOD__ . ':' . "acceptAction project:" . $projectId . ", point:" . count($points) . " \r\n", FILE_APPEND);

            $sql_project = "select * from project where user_id = {$user->userId} and local_id = '$toProjectId' and is_removed = 0 order by version desc";
            $toProject = $this->fetchOne($sql_project);

            $exsitsBlock = 0;

            if ($toProject) {
                $sql = "select * from survey_block where project_id = {$toProject['id']}";
                $blocks = $this->fetchAll($sql);

                foreach ($blocks as $block) {
                    if ($block['local_id'] != $toBlockId) {
                        $block["project_id"] = $projectId;
                        $oldBlockId = $block["id"];
                        unset($block["id"]);
                        unset($block["created_at"]);
                        $blockId = $this->insert("survey_block", $block);

                        $sql = "select * from flight_task where survey_block_id = $oldBlockId";
                        $tasks = $this->fetchAll($sql);

                        foreach ($tasks as &$task) {
                            $task["survey_block_id"] = $blockId;
                            unset($task["id"]);
                            unset($task["created_at"]);
                            $this->insert("flight_task", $task);
                        }
                    } else {
                        $block["project_id"] = $projectId;
                        $oldBlockId = $block["id"];
                        unset($block["id"]);
                        unset($block["created_at"]);
                        $blockId = $this->insert("survey_block", $block);
                        $exsitsBlock = $blockId;

                        $sql = "select * from flight_task where survey_block_id = $oldBlockId and local_id<>'$toTaskId'";
                        $tasks = $this->fetchAll($sql);

                        foreach ($tasks as &$task) {
                            $task["survey_block_id"] = $blockId;
                            unset($task["id"]);
                            unset($task["created_at"]);
                            $this->insert("flight_task", $task);
                        }
                    }
                }

            }

            $sql = "select * from survey_block where project_id = $oldProjectId and local_id = '{$assign['survey_local_id']}'";
            $blocks = $this->fetchAll($sql);

            foreach ($blocks as $block) {
                $block["project_id"] = $projectId;
                $oldBlockId = $block["id"];
                $block["local_id"] = $toBlockId;
                $block["survey_area_guid"] = $toBlockId;
                unset($block["id"]);
                unset($block["created_at"]);
                if ($exsitsBlock) {
                    $sql = "select * from flight_task where survey_block_id = $oldBlockId and local_id='{$assign['task_local_id']}'";
                    $tasks = $this->fetchAll($sql);

                    foreach ($tasks as &$task) {
                        $task["survey_block_id"] = $exsitsBlock;
                        $task["local_id"] = $toTaskId;
                        unset($task["id"]);
                        unset($task["created_at"]);
                        $this->insert("flight_task", $task);
                    }
                } else {
                    $blockId = $this->insert("survey_block", $block);

                    $sql = "select * from flight_task where survey_block_id = $oldBlockId and local_id='{$assign['task_local_id']}'";
                    $tasks = $this->fetchAll($sql);

                    foreach ($tasks as &$task) {
                        $task["survey_block_id"] = $blockId;
                        $task["local_id"] = $toTaskId;
                        unset($task["id"]);
                        unset($task["created_at"]);
                        $this->insert("flight_task", $task);
                    }
                }
            }

            $sql = "update project_assign set status = 2, type = $type, updated_at = now(), to_project_local_id = '$toProjectId', to_survey_local_id = '$toBlockId', to_task_local_id = '$toTaskId' where id = $id";
            $this->execute($sql);

            if (!empty($message)) {
                $sql = "insert into project_assign_message(project_assign_id, user_id, type, info) values($id, {$user->userId}, $type, '$message')";
                $this->execute($sql);
            }

            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            $this->returnError("分派失败：$e");
        }

        $token = $this->guid();
        $this->web_push(array(
            'action' => 'web_assign_accpet',
            'status' => '2',
            'data' => '',
            'message' => $user->name . '已接受了您的任务。' . $task['flight_task_name'],
            'token' => $token
        ), $fromUserId, $user->userId);


        $this->pc_push(array(
            'action' => 'pc_assign_accpet',
            'status' => '2',
            'data' => '',
            'message' => $user->name . '已接受了您的任务:' . $task['flight_task_name'],
        ), $fromUserId, $user->userId);

        $this->returnSuccess("操作成功");
    }

    // 拒绝接口
    public function denyAction()
    {
        $user = $this->getMonitorLoginUser();
        $id = $this->getPost("id");
        $message = $this->getPost("message");

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "denyAction id:$id \r\n", FILE_APPEND);

        $sql = "select * from project_assign where id = $id";
        $record = $this->fetchOne($sql);
        if (empty($record)) {
            $this->returnError("id不存在。");
        }


        if ($record["status"] != 0) {
            $this->returnError("该项目不是可以拒绝的状态");
        }

        $sql = "update project_assign set status = 3, updated_at = now() where id = $id";
        $this->execute($sql);

        if (!empty($message)) {
            $sql = "insert into project_assign_message(project_assign_id, user_id, type, info) values($id, {$user->userId}, 3, '$message')";
            $this->execute($sql);
        }

        $token = $this->guid();
        $this->web_push(array(
            'action' => 'web_assign_deny',
            'status' => '2',
            'data' => '',
            'message' => $user->name . '已拒绝您的任务。',
            'token' => $token
        ), $record["assign_from_user_id"], $user->userId);

        $this->pc_push(array(
            'action' => 'pc_assign_deny',
            'status' => '2',
            'data' => '',
            'message' => $user->name . '已拒绝您的任务。',
        ), $record["assign_from_user_id"], $user->userId);

        $this->returnSuccess("已拒绝任务。");
    }

    // 回复指派列表接口
    public function replyListAction()
    {
        $user = $this->getMonitorLoginUser();

        $id = $this->getPost("id");

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "replyAction id:$id\r\n", FILE_APPEND);

        $sql = "select m.id,m.project_assign_id,u.id as user_id,u.nickname,u.icon_url,m.type,m.info,m.created_at from project_assign_message as m LEFT JOIN user as u on m.user_id=u.id where project_assign_id = $id order by created_at asc";
        $record = $this->fetchAll($sql);


        $this->returnJson($record);
    }

    // 回复分享接口
    public function replyAction()
    {
        $user = $this->getMonitorLoginUser();
        $this->checkRequestParams(array(
                array(
                    "key" => "id",
                    "type" => "presence&number",
                    "message" => "id格式不合法"),
                array(
                    "key" => "message",
                    "type" => "presence",
                    "message" => "message为空"),
            )
        );
        $id = $this->getPost("id");
        $message = $this->getPost("message");

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "replyAction id:$id, message:$message \r\n", FILE_APPEND);

        $sql = "select * from project_assign where id = $id";
        $record = $this->fetchOne($sql);
        if (empty($record)) {
            $this->returnError("分享id不存在。");
        }

        $sql = "insert into project_assign_message(project_assign_id, user_id, type, info) values($id, {$user->userId}, 0, '$message')";
        $this->execute($sql);

        $toUserId = 0;
        if ($record["assign_from_user_id"] == $user->userId) {
            $toUserId = $record["assign_to_user_id"];
        } else {
            $toUserId = $record["assign_from_user_id"];
        }

        $this->pc_push(array(
            'action' => 'pc_assign_message',
            'status' => '2',
            "data" => array(
                'assign_id' => $id,
            ),
            'message' => $message,
            'token' => $this->guid()
        ), $toUserId, $user->userId);

        //        $this->requestTcp([
        //            'status' => 1,
        //            'from_id' => $user["id"],
        //            'to_id' => $toUserId,
        //            'action' => 'project_message',
        //            'data' => [
        //                'share_id' => $id,
        //                'message' => $message
        //            ],
        //            'message' => ''
        //        ],$this->getToken());

        $this->returnSuccess("回复成功。");
    }

    public function uploadAction()
    {

        $name = $this->getPost("appname");
        $version = $this->getPost("appversion");
        $md5 = $this->getPost("md5");

        $file = $this->getUploadFile();
        $path = "/{$file["name"]}";

        $uploadRet = Cosapi::upload($file["tmp_name"], "files", $path);


        $this->returnSuccess("上传成功。");
    }

    /**
     *  添加任务分派
     * @param $toUserId
     * @param $projectLocalId
     * @param $surveyLocalId
     * @param $taskLocalId
     * @param $projectWorkId
     */
    public function _addProjectAssign($toUserId, $projectLocalId, $surveyLocalId, $taskLocalId, $projectWorkId, $message)
    {
        $user = $this->getMonitorLoginUser();
        $id = 0;
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "get userId:" . $user->userId . ", user_id:$toUserId, project_local_id:$projectLocalId, survey_local_id:$surveyLocalId, task_local_id:$taskLocalId\r\n", FILE_APPEND);

        $sql = "select id from user where id = " . $toUserId;
        $toUser = $this->fetchOne($sql);
        if (empty($toUser)) {
            $this->returnError("用户不存在。");
        }

        $sql = "select id, local_id, project_name, created_at, updated_at, version, center_position_lng, center_position_lat, map_scale, user_id from project where user_id = " . $user->userId . " and local_id = '$projectLocalId' and is_removed = false order by version desc limit 1";
        $project = $this->fetchOne($sql);

        if (empty($project)) {
            $this->returnError("项目id:$projectLocalId 不存在。");
        }
        $projectId = $project["id"];
        $sql = "select id, local_id, project_id, created_at, updated_at, survey_area_name, block_type, survey_area_coordinate_points, home_lng, home_lat, work_area, work_time from survey_block where project_id = $projectId and local_id = '$surveyLocalId'";
        $block = $this->fetchOne($sql);
        if (empty($block)) {
            $this->returnError("区块id:$surveyLocalId 不存在。");
        }

        $blockId = $block["id"];
        $sql = "select * from flight_task where survey_block_id = $blockId and local_id='$taskLocalId'";
        $task = $this->fetchOne($sql);
        if (empty($task)) {
            $this->returnError("任务id:$taskLocalId 不存在。");
        }

//         $sql = "select id, status from project_assign where assign_to_user_id = $userId and project_local_id = '$projectLocalId' and survey_local_id = '$surveyLocalId' and task_local_id = '$taskLocalId' order by id desc";
        $sql = "select * from project_assign where assign_to_user_id = $toUserId and project_local_id = '$projectLocalId' and status = 2 order by updated_at desc";
        $assign = $this->fetchOne($sql);

        if ($assign) {

            $sql_project = "select * from project where user_id = $toUserId and local_id = '{$assign['to_project_local_id']}' and is_removed = 0 order by version desc";
            $toProject = $this->fetchOne($sql_project);

            if ($toProject) {
                $sql = "select * from project_assign where assign_to_user_id = $toUserId and project_local_id = '$projectLocalId' and survey_local_id = '$surveyLocalId' and status = 2 order by updated_at desc";
                $assign_block = $this->fetchOne($sql);

                if ($assign_block) {
                    $sql_block = "select * from survey_block where project_id = {$toProject['id']} and local_id = '{$assign_block['to_survey_local_id']}'";
                    $toBlock = $this->fetchOne($sql_block);

                    if ($toBlock) {
                        $sql = "select * from project_assign where assign_to_user_id = $toUserId and project_local_id = '$projectLocalId' and survey_local_id = '$surveyLocalId' and task_local_id = '$taskLocalId' and status = 2 order by updated_at desc";
                        $assign_task = $this->fetchOne($sql);

                        if ($assign_task) {
                            $sql_task = "select * from flight_task where survey_block_id = {$toBlock['id']} and local_id='{$assign_task['to_task_local_id']}'";
                            $toTask = $this->fetchOne($sql_task);

                            if ($toTask) {
                                if ($assign_task['status'] == '0' || $assign_task['status'] != '2') {
                                    $this->update('project_assign', array(
                                        'status' => 0,
                                        'project_id' => $projectId,
                                        'projectWork_id' => $projectWorkId,
                                        'version' => $project['version'],
                                        'updated_at' => date('Y-m-d H:i:s'),
                                    ), 'id=' . $assign_task['id']);

                                    $id = $assign_task['id'];
                                } elseif ($assign_task['status'] == '0' || $assign_task['status'] == '2') {
                                    $this->returnSuccess('任务已分派');
                                }
                            } else {
                                $id = $this->insert('project_assign', array(
                                    'assign_from_user_id' => $user->userId,
                                    'assign_to_user_id' => $toUserId,
                                    'status' => 0,
                                    'project_local_id' => $projectLocalId,
                                    'project_id' => $projectId,
                                    'survey_local_id' => $surveyLocalId,
                                    'task_local_id' => $taskLocalId,
                                    'to_project_local_id' => $assign_block['to_project_local_id'],
                                    'to_survey_local_id' => $assign_block['to_survey_local_id'],
                                    'projectWork_id' => $projectWorkId,
                                    'version' => $project['version'],
                                    'created_at' => date('Y-m-d H:i:s'),
                                    'updated_at' => date('Y-m-d H:i:s')
                                ), true);
                            }
                        } else {
                            $id = $this->insert('project_assign', array(
                                'assign_from_user_id' => $user->userId,
                                'assign_to_user_id' => $toUserId,
                                'status' => 0,
                                'project_local_id' => $projectLocalId,
                                'project_id' => $projectId,
                                'survey_local_id' => $surveyLocalId,
                                'task_local_id' => $taskLocalId,
                                'to_project_local_id' => $assign_block['to_project_local_id'],
                                'to_survey_local_id' => $assign_block['to_survey_local_id'],
                                'projectWork_id' => $projectWorkId,
                                'version' => $project['version'],
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s')
                            ), true);
                        }
                    } else {
                        $id = $this->insert('project_assign', array(
                            'assign_from_user_id' => $user->userId,
                            'assign_to_user_id' => $toUserId,
                            'status' => 0,
                            'project_local_id' => $projectLocalId,
                            'project_id' => $projectId,
                            'survey_local_id' => $surveyLocalId,
                            'task_local_id' => $taskLocalId,
                            'to_project_local_id' => $assign['to_project_local_id'],
                            'projectWork_id' => $projectWorkId,
                            'version' => $project['version'],
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s')
                        ), true);
                    }
                } else {
                    $id = $this->insert('project_assign', array(
                        'assign_from_user_id' => $user->userId,
                        'assign_to_user_id' => $toUserId,
                        'status' => 0,
                        'project_local_id' => $projectLocalId,
                        'project_id' => $projectId,
                        'survey_local_id' => $surveyLocalId,
                        'task_local_id' => $taskLocalId,
                        'to_project_local_id' => $assign['to_project_local_id'],
                        'projectWork_id' => $projectWorkId,
                        'version' => $project['version'],
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ), true);
                }
            } else {
                $id = $this->insert('project_assign', array(
                    'assign_from_user_id' => $user->userId,
                    'assign_to_user_id' => $toUserId,
                    'status' => 0,
                    'project_local_id' => $projectLocalId,
                    'project_id' => $projectId,
                    'survey_local_id' => $surveyLocalId,
                    'task_local_id' => $taskLocalId,
                    'projectWork_id' => $projectWorkId,
                    'version' => $project['version'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ), true);
            }
        } else {
            $id = $this->insert('project_assign', array(
                'assign_from_user_id' => $user->userId,
                'assign_to_user_id' => $toUserId,
                'status' => 0,
                'project_local_id' => $projectLocalId,
                'project_id' => $projectId,
                'survey_local_id' => $surveyLocalId,
                'task_local_id' => $taskLocalId,
                'projectWork_id' => $projectWorkId,
                'version' => $project['version'],
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ), true);
        }


        if (!empty($message) && !empty($id)) {
            $sql = "insert into project_assign_message(project_assign_id, user_id, type, info) values($id, {$user->userId}, 0, '$message')";
            $this->execute($sql);
        }

        $token = $this->guid();
        $this->web_push(array(
            'action' => 'web_assign',
            'status' => '2',
            'data' => '',
            'message' => $user->name . '向您分派了任务:' . $task['flight_task_name'],
            'token' => $token
        ), $toUserId, $user->userId);

        //发送给管家端
        $this->pc_push(array(
            'action' => 'pc_assign',
            'status' => '2',
            'data' => '',
            'message' => $user->name . '向您分派了任务:' . $task['flight_task_name'],
        ), $toUserId, $user->userId);
        return true;
    }

    private function _addProjectWork($projectId)
    {
        $user = $this->getMonitorLoginUser();
        $sql = "select id, project_name from project where id = " . $projectId;
        $project = $this->fetchOne($sql);
        if (empty($project)) {
            $this->returnError("项目" . $project['project_name'] . "不存在。");
        } else {
            $id = $this->insert('project_work', array(
                "user_id" => $user->userId,
                'project_id' => $projectId,
                'work_name' => $project['project_name'],
                'created_at' => date('Y-m-d H:i:s')
            ));

            return $id;
        }
        return false;
    }

}